package boot.spring.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import boot.spring.po.Mail;
import boot.spring.po.TopicMail;
import boot.spring.service.impl.ProducerImpl;
import boot.spring.service.impl.PublisherImpl;


@Controller
public class RabbitMQController {


    @Autowired
    ProducerImpl producer;

    @Autowired
    PublisherImpl publisher;

    /**
     * f1 生产者-消费者模型，向队列生产消息
     *
     * @param mail
     * @throws Exception
     */
    @RequestMapping(value = "/produce", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public void produce(@ModelAttribute("mail") Mail mail) throws Exception {
        producer.sendMail("myqueue", mail);
    }

    /**
     * f2 发布-订阅模型，向所有队列广播消息
     *
     * @param mail
     * @throws Exception
     */
    @RequestMapping(value = "/topic", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public void topic(@ModelAttribute("mail") Mail mail) throws Exception {

        System.out.println("==============f2. 发布-订阅模型，向所有队列广播消息==============");
        publisher.publishMail(mail);
    }


    /**
     * f3  直连交换机模型，向指定的routing key发送消息
     *
     * @param mail
     */
    @RequestMapping(value = "/direct", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public void direct(@ModelAttribute("mail") TopicMail mail) {
        Mail m = new Mail(mail.getMailId(), mail.getCountry(), mail.getWeight());

        System.out.println("======direct--- mail.getRoutingkey()===========" + mail.getRoutingkey());
        publisher.senddirectMail(m, mail.getRoutingkey());
    }

    /**
     * f4 topic交换机模型，向匹配的routing key发送消息
     *
     * @param mail
     */
    @RequestMapping(value = "/mytopic", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public void topic(@ModelAttribute("mail") TopicMail mail) {
        Mail m = new Mail(mail.getMailId(), mail.getCountry(), mail.getWeight());
        publisher.sendtopicMail(m, mail.getRoutingkey());
    }


    @RequestMapping("demo")
    public String demo() {
        return "demo";
    }


}
